package mx.gob.imss.reiman.clientes.service.impl;

import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;

import mx.gob.imss.reiman.clientes.service.SOAPService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

/**
 * 
 * @author Alberto Dzul Calvillo
 * @version 1.0
 * 
 */
@Service("soapService")
public class SOAPServiceImpl implements SOAPService {
	private static Logger logger = LoggerFactory
			.getLogger(SOAPServiceImpl.class);

	public SOAPMessage enviar(Node node, String ep)
			throws MalformedURLException, UnsupportedOperationException,
			SOAPException {
		SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
		SOAPConnection connection = factory.createConnection();
		SOAPMessage message = MessageFactory.newInstance().createMessage();
		SOAPPart part = message.getSOAPPart();
		SOAPEnvelope envelope = part.getEnvelope();
		SOAPBody body = envelope.getBody();
		body.addDocument((Document) node);
		URL endpoint = new URL(ep);
		SOAPMessage response = null;
		try {
			if (logger.isDebugEnabled()) {
				message.writeTo(System.out);
			}
			response = connection.call(message, endpoint);
			if (logger.isDebugEnabled()) {
				response.writeTo(System.out);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			connection.close();
		}
		return response;
	}
}